from playwright.sync_api import sync_playwright

from xunter_utils.xunter_requests import ChromeClient


class Antispider8Spider(ChromeClient):
    def __init__(self):
        super().__init__()
        self.host = 'https://antispider8.scrape.center'

        context = sync_playwright().start()  # 开始执行playwright
        browser = context.chromium.launch(headless=False)  # 创建有头谷歌浏览器
        self.page = browser.new_page()  # 创建一个页面

        self.page.route(
            '**/chunk-51935b2c.7a777070.js',
            lambda route: route.fulfill(path=r'./ChromeOverrides/antispider8.scrape.center/js/chunk.js')
        )  # 把网络请求中的chunk-51935b2c.7a777070.js替换成本地修改好的js文件

        self.page.goto(self.host)

    def get_token(self, api_index: str):
        return self.page.evaluate(
            """
            ()=>{
            return window.g_token('%s')
            }
            """ % api_index
        )

    def get_page(self, page: int):
        api_index = '/api/movie'
        limit = 10
        offset = (page - 1) * limit
        res = self.send_request(
            url=self.host + api_index,
            params=dict(
                limit=limit,
                offset=offset,
                token=self.get_token(api_index),
            )
        )
        return res.json()


if __name__ == '__main__':
    client = Antispider8Spider()
    for i in range(1, 10):
        data = client.get_page(i)
        print(data)
